package spark_core.operate_transform.keyvalue;

import java.util.Arrays;
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaPairRDD;
import org.apache.spark.api.java.JavaSparkContext;
import scala.Tuple2;


/**
 * @author shihb
 * @date 2020/1/8 11:43
 * 根据key,进行分组，相同key的value会放在同一个list里面
 */
public class GroupByKeyDemo {

  public static void main(String[] args) {
    //local模式,创建SparkConf对象设定spark的部署环境
    SparkConf sparkConf = new SparkConf().setMaster("local[*]").setAppName("mark rdd");
    //创建spark上下文对象（这边是java上下文）
    JavaSparkContext sc = new JavaSparkContext(sparkConf);

    //key-value的方法要pairRdd才能调用,所以创建JavaPairRDD
    JavaPairRDD inputPairRDD = sc.parallelizePairs(Arrays
            .asList(new Tuple2(1, "aa"), new Tuple2(2, "bb"), new Tuple2(3, "cc"), new Tuple2(1, "dd")));

    JavaPairRDD groupByRdd = inputPairRDD.groupByKey();
    groupByRdd.glom().collect().forEach(System.out::println);
    //结果
    //[]
    //[(1,[aa, dd])]
    //[(2,[bb])]
    //[(3,[cc])]

    //停止
    sc.stop();

  }
}
